#include "Blockqueue.hpp"
#include "Task.hpp"
#include <iostream>
#include <queue>
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
using namespace std;

const char *g_op = "+-*/";

void *consumer(void *args)
{
    Blockqueue<Task> *bq = static_cast<Blockqueue<Task> *>(args);
    while (true)
    {
        // int data = bq->pop();
        Task data = bq->pop();
        data.run();
        cout << "执行了一个任务: " << data._x<<" "<<data._op<<" "<<data._y<<" = "<< data.result() << endl;
        //////////////////cout << "消费了一个数据: " <<  << endl;

        sleep(1);
    }
}

void *producer(void *args)
{
    // Blockqueue<int> *bq = static_cast<Blockqueue<int> *>(args);
    Blockqueue<Task> *bq = static_cast<Blockqueue<Task> *>(args);
    // int data = 0;
    while (true)
    {
        char op = g_op[rand() % 4];
        Task tk(rand() % 100, rand() % 100, op);
        bq->push(tk);
        // bq->push(data);
        // data++;
        // cout << "生产了一个数据：" << tk << endl;
        cout << "发送一个任务" << tk._x<<tk._op<<tk._y<<endl;
        // sleep(1);
    }
}

int main()
{
    srand(time(NULL));
    Blockqueue<Task> *bq = new Blockqueue<Task>();
    pthread_t c[3];
    pthread_t p[5];

    for (int i = 0; i < 3; i++)
    {
        pthread_create(c + i, nullptr, consumer, bq);
    }

    for (int i = 0; i < 5; i++)
    {
        pthread_create(p + i, nullptr, producer, bq);
    }

    for (int i = 0; i < 3; i++)
    {
        pthread_join(c[i], nullptr);
    }

    for (int i = 0; i < 5; i++)
    {
        pthread_join(p[i], nullptr);
    }

    delete bq;
    return 0;
}
